package com.newtouch.cq.lang.page;


import cn.hutool.core.util.StrUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import java.io.Serializable;
import java.util.List;

public interface GenericPageOrderAble extends GenericPageAble, Serializable {

    List<Sort.Order> getOrderList();

    GenericPageOrderAble addOrder(Sort.Order order);

    GenericPageOrderAble setOrderList(List<Sort.Order> orderList);

    /**
     * 增加排序，默认按照 createTime desc
     *
     * @return
     */
    @Override
    default GenericPageOrderAble defSort() {
        return addSort("", SORT_DEF, Direction.DESC);
    }

    /**
     * 增加排序
     *
     * @param alias 字段的对象别名
     * @param sort  排序字段
     * @return
     */
    default GenericPageOrderAble addSort(String alias, String sort) {
        return addSort(alias, SORT_DEF, null);
    }

    /**
     * 增加排序
     *
     * @param sort 排序字段
     * @return
     */
    default GenericPageOrderAble addSort(String sort) {
        return addSort(null, sort);
    }

    /**
     * 增加排序
     *
     * @param sort      排序字段
     * @param direction ASC DESC
     * @return
     */
    default GenericPageOrderAble addSort(String sort, Direction direction) {
        return addSort(null, sort, direction);
    }

    /**
     * 增加排序
     *
     * @param alias     字段的对象别名
     * @param sort      排序字段
     * @param direction ASC DESC
     * @return
     */
    default GenericPageOrderAble addSort(String alias, String sort, Direction direction) {
        if (StrUtil.isNotBlank(sort)) {
            if (StrUtil.isNotBlank(alias)) {
                sort = alias + "." + sort;
            }
            addOrder(new Sort.Order(direction, sort));
        }
        return this;
    }

    default GenericPageOrderAble buildPageFromOther(GenericPageOrderAble orderAble) {
        setCurrent(orderAble.getCurrent());
        setSize(orderAble.getSize());
        setOrderList(orderAble.getOrderList());
        return this;
    }

    default Pageable buildPageable() {
        return PageRequest.of(getCurrent() - 1, getSize(), buildSort());
    }

    default Sort buildSort() {
        return Sort.by(getOrderList());
    }

}
